
package testemodulorede;

import java.net.*;
import java.io.*;

public class ClientModule implements LanModule {

       private Socket sock;
       private PrintWriter writer;
       private BufferedReader reader;
       private String mensagem;
       private GamePanel game;
       
       public ClientModule( GamePanel _game, String _playerConfig, String _ip, int _porta ){

            conectar( _ip, _porta );
            
            try{

                this.writer.println( _playerConfig );
                this.writer.flush();

                //this.mensagem = this.reader.readLine();

            }
            catch( Exception ex ){

                ex.printStackTrace();

            }

            this.game = _game;

       }

       public String getMensagem(){

           return this.mensagem;

       }

       public void conectar( String _ip, int _porta ){

           try{

               this.sock = new Socket( _ip, _porta );
               InputStreamReader streamReader = new InputStreamReader( this.sock.getInputStream() );
               this.reader = new BufferedReader( streamReader );
               this.writer = new PrintWriter( this.sock.getOutputStream() );

           }
           catch(IOException ex){

               ex.printStackTrace();

           }

       }

       public void startService(){

           try{
                while( ( this.mensagem = this.reader.readLine() ) != null ){

                    this.game.gameAction( this.mensagem );


                }
           }
           
           catch(Exception ex){

               ex.printStackTrace();

           }

       }

       public synchronized void sendPackage(String _message){

           try{

                writer.println(_message);
                writer.flush();

            }
            catch(Exception ex){

                ex.printStackTrace();

            }

       }

}